<?php
namespace app\dboard\controller;
use think\captcha;
use think\facade\Cookie;
use think\facade\Session;
use think\facade\Url;
use think\Db;
class Teacheradmin extends Tbase
{
    public function initialize() {
        parent::initialize();
        $returnUrl=Url::build('dboard/tlogin/sign');
        if(!isset($this->TAdminAccount['AdminID']) || intval($this->TAdminAccount['AdminID'])<=0){
            if($this->request->isAjax()){
                return $this->print_result(['Code'=>9999,'Msg'=>'请登录']);
            }
            return $this->redirect($returnUrl);
        }
    }
    public function courseware_lists(){
        if ($this->request->isAjax()) {
            $input = $this->request->param(false);
            $page_limit      = isset($input['length'])?$input['length']:10;
            $page_start      = isset($input['start'])?$input['start']:0;
            $p = 1;
            if ($page_start > 0) {
                $p = ceil($page_start / ($page_limit - 1));
            }
            $sid = isset($input['sid'])?$input['sid']:0;
            if (!$sid) {
                $this->res_data['Msg'] = "缺少必填信息";
                return $this->print_result($this->res_data);
            }
            // $store= Db::name('store')->where([['id','=',$sid]])->find();
            // if (!$store) {
            //   $this->res_data['Msg'] = "无此门店";
            //   return $this->res_data;
            // }
            $where = [];
            $where[] = ['ca.teacher_id','=',$this->TAdminAccount['AdminID']];
            $where[] = ['ca.type','=',2];
            $where[] = ['ca.status','=',1];
            $where[] = ['c.status','=',1];
            $where[] = ['ca.start_time','<',time()];
            $where[] = ['ca.end_time','>=',time()];
            $where[] = ['c.name','in',['ppt','思维导图']];
            if (isset($input['name']) && $input['name']) {
                $where[] = ['c.course','like','%'.$input['name'].'%'];
                $where[] = ['cc.status','=',1];
                $field = '*';
                $count=Db::name('courseware_authorize')->alias('ca')->leftJoin('courseware c','ca.course_id=c.course_id')->leftJoin('courseware_course cc','c.course=cc.name')->where($where)->count();
                $list  = Db::name('courseware_authorize')->alias('ca')
                      ->leftJoin('courseware c','ca.course_id=c.course_id')
                      ->leftJoin('courseware_course cc','c.course=cc.name')
                      ->field('c.*')
                      ->where($where)
                      ->order('cc.sort ASC')
                      ->limit($page_start, $page_limit)->select();
                foreach($list as &$v){
                    $v['create_date'] = date('Y-m-d H:i',$v['create_time']);
                    $file = json_decode($v['file'],1);
                    $v['content'] = '';
                    if (count($file)) {
                        foreach ($file as $key => $value) {
                            if (isset($value[2]))
                                $v['content'] .= $value[2].',';
                        }
                        $v['content'] = trim($v['content'],',');
                    }
                }
                
                $this->res_data['Msg']='OK';
                $this->res_data['Code']=0;
                $this->res_data['Data']=['courseware'=>$list,'Data'=>$list,'recordsTotal'=>$count];
                $this->res_data['recordsTotal']=$count;
                return $this->print_result($this->res_data);
            }
            if (isset($input['course_id']) && $input['course_id']) {
                // 最末一级的course_id
                $courseware_course = Db::name('courseware_course')->field('id,name,level')->where(['pid'=>$input['course_id'],'status'=>1])->select();
                if (!$courseware_course) {
                    $where[] = ['ca.course_id','=',$input['course_id']];
                } else {
                    $arr = [];
                    foreach ($courseware_course as $key => $value) {
                        if ($value['level']==3) {
                            $arr[] = $value['id'];
                        } else {
                            $courseware_course2 = Db::name('courseware_course')->field('id,name,level')->where(['pid'=>$value['id'],'status'=>1])->select();
                            if ($courseware_course2) {
                                foreach ($courseware_course2 as $k => $v) {
                                    if ($v['level']==3) {
                                        $arr[] = $v['id'];
                                    }
                                }
                            }
                        }
                    }
                    $where[] = ['ca.course_id','in',$arr];
                }
            }
            $field = '*';
            $count=Db::name('courseware_authorize')->alias('ca')->leftJoin('courseware c','ca.course_id=c.course_id')->where($where)->count();
            $list  = Db::name('courseware_authorize')->alias('ca')
                  ->leftJoin('courseware c','ca.course_id=c.course_id')
                  ->leftJoin('courseware_course cc','c.course=cc.name')
                  ->field('c.*')
                  ->where($where)
                  ->order('cc.sort ASC')
                  ->limit($page_start, $page_limit)->select();
            foreach($list as &$v){
                $v['create_date'] = date('Y-m-d H:i',$v['create_time']);
                $file = json_decode($v['file'],1);
                $v['content'] = '';
                if (count($file)) {
                    foreach ($file as $key => $value) {
                        if (isset($value[2]))
                            $v['content'] .= $value[2].',';
                    }
                    $v['content'] = trim($v['content'],',');
                }
            }
            
            $this->res_data['Msg']='OK';
            $this->res_data['Code']=0;
            $this->res_data['Data']=['courseware'=>$list,'Data'=>$list,'recordsTotal'=>$count];
            $this->res_data['recordsTotal']=$count;
            return $this->print_result($this->res_data);
        }
        return view('teacheradmin/courseware_lists');
    }
    public function edit_courseware(){
        $input = $this->request->param(false);
        $id = isset($input['id'])?$input['id']:0;
        $courseware = [];
        if (!$id) {
            return $this->print_result(['Code'=>1,'Msg'=>'缺少参数']);
        }
        $courseware = Db::name('courseware')->where(['id'=>$id])->find();
        $courseware['has_video'] = 0;
        $courseware['has_pdf'] = 0;
        $courseware['video'] = [];
        $courseware['pdf'] = [];
        if (isset($courseware['file']) && $courseware['file']) {
            $courseware['file'] = json_decode($courseware['file'],1);
            if (is_array($courseware['file']) && count($courseware['file'])) {
                foreach ($courseware['file'] as $key => &$value) {
                    $multi_file = [];
                    $ex = explode(',', trim($value[1]));
                    if (count($ex)) {
                        foreach ($ex as $k => &$mf) {
                            // if (explode('.', $mf)[1]!='ppt' && explode('.', $mf)[1]!='pptx') continue;
                            $mf_name = Db::name('file')->where(['path'=>$mf])->value('name');
                            if (!$mf_name) {
                                if ($value[2]=='视频') {
                                    $mf_name = '视频';
                                } else {
                                    $mf_name = '文件';
                                }
                            }
                            $mf = config('upload_domain').$mf;
                            $multi_file[$k] = ['mf_name'=>$mf_name,'mf'=>$mf];
                        }
                    }
                    $value[3] = $multi_file;
                    if ($value[2]=='视频') {
                        $courseware['has_video'] = 1;
                        $courseware['video'] = array_merge($courseware['video'],$multi_file);
                    } else {
                        $courseware['has_pdf'] = 1;
                        $courseware['pdf'] = array_merge($courseware['pdf'],$multi_file);
                    }
                }
            }
        }
        $pid3 = $courseware['course_id'];
        $courseware_course_name3 = $courseware['course'];
        $courseware_course2 = Db::name('courseware_course')->where(['id'=>$pid3])->field('pid,name')->find();
        $pid2 = $courseware_course2['pid'];
        $courseware_course_name2 = $courseware_course2['name'];
        $courseware_course1 = Db::name('courseware_course')->where(['id'=>$pid2])->field('pid,name')->find();
        $pid1 = $courseware_course2['pid'];
        $courseware_course_name1 = $courseware_course1['name'];
        $this->assign('courseware',$courseware);
        $this->assign('pid1',$pid1);
        $this->assign('pid2',$pid2);
        $this->assign('pid3',$pid3);
        $this->assign('courseware_course_name1',$courseware_course_name1);
        $this->assign('courseware_course_name2',$courseware_course_name2);
        $this->assign('courseware_course_name3',$courseware_course_name3);
        return view('teacheradmin/edit_courseware');
    }
    public function authorize(){
        $input = $this->request->param(false);
        $id = isset($input['id'])?$input['id']:0;
        $sid = isset($this->AdminAccount['sid'])?$this->AdminAccount['sid']:0;
        $courseware = [];
        if (!$id || !$sid) {
            return $this->print_result(['Code'=>1,'Msg'=>'缺少参数']);
        }
        $courseware = Db::name('courseware')->where('id',$id)->find();
        $teacher = Db::name('teacher')->where(['status'=>1,'sid'=>$sid])->select();
        if ($teacher) {
            foreach ($teacher as $key => &$value) {
                $value['avatar'] = config('upload_domain').$value['avatar'];
            }
        }
        // 已授权的店
        $courseware_authorize = Db::name('courseware_authorize')->where(['courseware_id'=>$id,'status'=>1,'type'=>2])->value('group_concat(teacher_id) as teacher_ids');
        $this->assign('id',$id);
        $this->assign('courseware',$courseware);
        $this->assign('store',$teacher);
        $this->assign('courseware_authorize',$courseware_authorize);
        return view('courseware/authorize');
    }
    public function editCoursewareauthorize()
    {
        if (!$this->request->isAjax()) {
            $this->res_data['Msg'] = '请求方式错误';
            return $this->print_result($this->res_data);
        }
        $param    = $this->request->param(false);
        $courseware= Controller('Courseware', 'logic');
        $result            = $courseware->updateCoursewareauthorize($param,$this->AdminAccount['sid']);
        return $this->print_result($result);
    }
    public function edit_pwd(){
        return view('teacheradmin/edit_pwd');
    }
   public function editShopPwd(){
        if (!$this->request->isAjax()) {
            $this->res_data['Msg'] = '请求方式错误';
            return $this->print_result($result);
        }
        $param    = $this->request->param(false);
        
        $id = isset($param['id']) ? trim($param['id']):'';
        $oldpwd = isset($param['oldpwd']) ? trim($param['oldpwd']):'';
        $newpwd = isset($param['newpwd']) ? trim($param['newpwd']):'';
        $newpwd_confirm = isset($param['newpwd_confirm']) ? trim($param['newpwd_confirm']):'';
        if (!$id || !$oldpwd || !$newpwd || !$newpwd_confirm ) {
            $this->res_data['Msg'] = "缺少必填信息";
            return $this->print_result($this->res_data);
        }
        if ($newpwd != $newpwd_confirm ) {
            $this->res_data['Msg'] = "新密码两次输入不一致";
            return $this->print_result($this->res_data);
        }
        $password=get_admin_pwd($oldpwd);
        $teacher= Db::name('teacher')->where([['id','=',$id],['pwd','=',$password]])->find();
        if (!$teacher) {
            $this->res_data['Msg'] = "旧密码错误";
            return $this->print_result($this->res_data);
        }
    
        $data['pwd'] =get_admin_pwd($newpwd);
        $data['updatetime'] =time();
        $data['token'] = '';
        $sdata = Db::name('teacher')->where([['id','=',$id]])->data($data)->update();
        if(!$sdata) {
            //Db::rollback();
            $this->res_data['Msg'] = '编辑失败';
            return $this->print_result($this->res_data);
        }

        $this->res_data['Msg'] = '成功';
        $this->res_data['Code'] = 0;
        return $this->print_result($this->res_data);
   }
    // 所属课程的下级
    public function courseware_course_son()
    {
        // if (!$this->request->isAjax()) {
        //     $this->res_data['Msg'] = '请求方式错误';
        //     return $this->print_result($this->res_data);
        // }
        $param    = $this->request->param(false);
        $pid = isset($param['pid'])?intval($param['pid']):0;
        $courseware_course = Db::name('courseware_course')->field('id,name')->where(['pid'=>0,'status'=>1])->select();
        foreach ($courseware_course as $key => $value) {
            $child = Db::name('courseware_course')->field('id,name')->where(['pid'=>$value['id'],'status'=>1])->select();
            if ($child) {
                foreach ($child as $k => $v) {
                    $child2 = Db::name('courseware_course')->field('id,name')->where(['pid'=>$v['id'],'status'=>1])->select();
                    $child[$k]['child'] = $child2;
                }
            }
            $courseware_course[$key]['child'] = $child;
        }
        $this->res_data['Msg'] = '成功';
        $this->res_data['Data'] = $courseware_course;
        $this->res_data['Code'] = 0;
        return $this->print_result($this->res_data);
    }
}
